const express = require('express');
const router = express.Router();

const {getUnix} = require('../../model/tools');
const ArticleCateModel = require('../../model/articleCateModel');
const mongoose = require('../../model/core');

router.get('/', async (req, res)=>{
  let result = await ArticleCateModel.aggregate([
    {
      $lookup: {
        from: 'article_cate',
        localField: '_id',
        foreignField: 'pid',
        as: 'items'
      }
    },
    {
      $match: {
        pid: '0'
      }
    }
  ]);
  res.render('admin/articleCate/index.html', {
    list: result
  })
});

router.get('/add', async (req, res)=>{
  let topCateList = await ArticleCateModel.find({pid: '0'});
  // console.log(topCateList);
  res.render('admin/articleCate/add.html', {
    cateList: topCateList
  })
});

router.post('/doAdd', async (req, res)=>{
  // 注意pid类型
  if(req.body.pid != '0'){
    req.body.pid = mongoose.Types.ObjectId(req.body.pid);
  }
  req.body.add_time = getUnix();
  let result = new ArticleCateModel(req.body);
  await result.save();
  res.redirect(`/${req.app.locals.adminPath}/articleCate`);
});

router.get('/edit', async (req, res)=>{
  let id = req.query.id;
  let result = await ArticleCateModel.find({_id: id});
  let topCateList = await ArticleCateModel.find({pid: '0'});
  res.render('admin/articleCate/edit.html',{
    list: result[0],
    cateList: topCateList
  })
});

router.post('/doEdit', async (req, res)=>{
  try {
    // 注意pid类型
    if(req.body.pid != '0'){
      req.body.pid = mongoose.Types.ObjectId(req.body.pid);
    }
    await ArticleCateModel.updateOne({_id: req.body.id}, req.body);
    res.redirect(`/${req.app.locals.adminPath}/articleCate`);
  } catch (error) {
    res.render('admin/public/error.html',{
      message: '删除轮播图失败',
      redirectUrl: `/${req.app.locals.adminPath}/articleCate/edit`
    })
  }
});

router.get('/delete', async (req, res)=>{
  let id = req.query.id;
  var subResult = await ArticleCateModel.find({pid: mongoose.Types.ObjectId(id)});
  if(subResult.length>0){
    // 含有子分类，不允许删除
    res.render('admin/public/error.html',{
      message: '当前分类无法删除，请删除其子分类后重试',
      redirectUrl: `/${req.app.locals.adminPath}/articleCate`
    })
  }else{
    await ArticleCateModel.deleteOne({_id: id});
    res.render('admin/public/success.html',{
      message: '删除分类成功',
      redirectUrl: `/${req.app.locals.adminPath}/articleCate`
    })
  }
});

module.exports = router;